import { Injectable } from '@nestjs/common'
import { Repository } from 'typeorm'
import ProjectEntity from '@main/db/entity/ProjectEntity'
import { InjectRepository } from '@nestjs/typeorm'
import PageResult from '@main/bo/PageResult'
import DataRepeatException from '@main/exception/DataRepeatException'
import { ApiService } from './ApiService'

@Injectable()
export class ProjectService {
  constructor(
    @InjectRepository(ProjectEntity)
    private repository: Repository<ProjectEntity>,
    private readonly apiService: ApiService
  ) {}

  async page(current: number, size: number) {
    const ret = await this.repository
      .createQueryBuilder()
      .skip((current - 1) * size)
      .take(size)
      .orderBy('id', 'DESC')
      .getManyAndCount()
    return PageResult.builder(current, size, ret[0], ret[1])
  }

  async add(entity: ProjectEntity): Promise<number> {
    const count = await this.repository.createQueryBuilder().andWhere('flag = :flag', { flag: entity.flag }).getCount()
    if (count != 0) {
      throw new DataRepeatException('项目唯一标识重复!')
    }
    const ret = await this.repository.createQueryBuilder().insert().into(ProjectEntity).values([entity]).execute()
    return ret.raw
  }

  async modify(entity: ProjectEntity) {
    const tmp = await this.repository.createQueryBuilder().andWhere('flag = :flag', { flag: entity.flag }).getOne()
    if (tmp && tmp.id !== entity.id) {
      throw new DataRepeatException('项目唯一标识重复!')
    }
    const ret = await this.repository
      .createQueryBuilder()
      .update(ProjectEntity)
      .set(entity)
      .whereInIds(entity.id)
      .execute()
    return ret.affected
  }

  async remove(ids: number[]) {
    if (!ids || ids.length === 0) return
    await this.repository.createQueryBuilder().delete().from(ProjectEntity).whereInIds(ids).execute()
    await this.apiService.removeByProjectIds(ids)
  }
}
